package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @author ：李帅
 * @date ：Created in 2022年06月08日
 * @description ：登录controller
 * @version: 1.0
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class LoginController {
    @Autowired
    private MemberService MemberService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map){
        log.info("接收到的用户手机号map:{}"+map);
        //录入的手机号
        String telephone = map.get("telephone").toString();
        //录入的验证码
        String validateCode = map.get("validateCode").toString();
        //redis的键
        String phoneKey = "MOBILE_SIGNIN"+telephone;
        //获取redis中的验证码
        String code = redisTemplate.opsForValue().get(phoneKey)+"";
        log.info("redis里的验证码是"+code);
        //进行比较
        if (StringUtils.isNotEmpty(validateCode) && validateCode.equals(code)){
            //根据手机号查询
            Member member = MemberService.getMemberByPhone(telephone);
            if (member==null){
                Member member1 = new Member();
                //手机号存进去
                member1.setPhoneNumber(telephone);
                //设置注册时间
                member1.setRegTime(new Date());
                //保存
                MemberService.addMember(member1);
            }

            return new Result(true,MessageConst.LOGIN_SUCCESS);
        }

        return new Result(false, MessageConst.LOGIN_FAIL);
    }
}
